package com.luo.demo;

/**
 * @Author: luosiyu
 * @Description: 检索字符串出现的次数
 * @Version: 1.0
 */
public class CheckString {
    public static void main(String[] args) {
        String info = "这些年一个人，风也过，雨也走，有过泪，有过错 ,\n" +
                "还记得坚持甚么，真爱过才会懂，会寂寞会回首，终有梦终有你在心中。\n" +
                "朋友一生一起走，那些日子不再有，一句话，一辈子，一生情，一杯酒。\n" +
                "朋友朋友朋友不曾孤单过，一声朋友你会懂，还有伤，还有痛，还要走，还有我。朋友";
        String select = "朋友";
        checkString(info,select);
        checkStringSub(info,select);
        checkStringSplit(info,select);
        checkStringRep(info,select);
    }

    public static void checkString(String info,String select){
        int count = 0;
        int start = 0;
        int index = select.length();
        while(info.indexOf(select,start)!=-1){
            count++;
            start = info.indexOf(select,start)+index;
        }
        System.out.println(select+"出现的次数："+count);
    }

    public static void checkStringSub(String info,String select){
        int count = 0;
        int start = 0;
        int index = select.length();
        while((start = info.indexOf(select))!=-1){
            count++;
            info = info.substring(start+index);
        }
        System.out.println(select+"出现的次数："+count);
    }

    public static void checkStringSplit(String info,String select){
        String[] split = info.split(select);
        int count = info.endsWith(select) ? split.length :split.length-1;
        System.out.println(select+"出现的次数："+count);
    }

    public static void checkStringRep(String info,String select) {
        int a = info.length();
        int b = info.replace(select,"").length();
        int c = select.length();
        System.out.println(select + "出现的次数：" +(a-b)/c );
    }
}
